<!DOCTYPE html>
<html>
<head>
    <title>基于Promise模式</title>
    <meta charset="utf-8"/>
    <script>
        var Promise = function () {
            /* initialize promise */
        };
        Promise.prototype.then = function (onResolved, onRejected) {
            /* invoke handlers based upon state transition */
        };
        Promise.prototype.resolve = function (value) {
            /* move from unfulfilled to resolved */
        };

        Promise.prototype.reject = function (error) {
            /* move from unfulfilled to rejected */
        }

        function searchTwitter(term) {

            var url, xhr, results, promise;
            url = 'http://search.twitter.com/search.json?rpp=100&q=' + term;
            promise = new Promise();
            xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);

            xhr.onload = function (e) {
                if (this.status === 200) {
                    results = JSON.parse(this.responseText);
                    promise.resolve(results);
                }
            };

            xhr.onerror = function (e) {
                promise.reject(e);
            };

            xhr.send();
            return promise;
        }

        function loadTweets() {
            var container = document.getElementById('container');
            searchTwitter('#IE10').then(function (data) {
                data.results.forEach(function (tweet) {
                    var el = document.createElement('li');
                    el.innerText = tweet.text;
                    container.appendChild(el);
                });
            }, handleError);
        }

        ///////////////////看看多个Ajax请求的并发协作////////////////////////
        Promise.when = function () {
            /* handle promises arguments and queue each */
        };

        Promise.prototype.then = function (onResolved, onRejected) {
            /* invoke handlers based upon state transition */
        };

        var container, promise1, promise2;
        container = document.getElementById('container');
        promise1 = searchTwitter('#IE10');
        promise2 = searchTwitter('#IE9');
        Promise.when(promise1, promise2).then(function (data1, data2) {
            /* Reshuffle due to date */
            var totalResults = concatResults(data1.results, data2.results);
            totalResults.forEach(function (tweet) {
                var el = document.createElement('li');
                el.innerText = tweet.text;
                container.appendChild(el);
            });
        }, handleError);
    </script>
</head>
<body>

</body>
</html>